
Imports MIMS.WRS.Business
Imports MIMS.WRS.Entities
Imports MyFramework

Public Class StockReportHeader
    Inherits System.Web.UI.UserControl

#Region " Web Form Designer Generated Code "

    'This call is required by the Web Form Designer.
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()

    End Sub
    Protected WithEvents ddlConPoint As System.Web.UI.WebControls.DropDownList
    Protected WithEvents txtDiscount As System.Web.UI.WebControls.TextBox
    Protected WithEvents chkShowFOB As System.Web.UI.WebControls.CheckBox
    Protected WithEvents ltrJS As System.Web.UI.WebControls.Literal
    Protected WithEvents txtQty As System.Web.UI.WebControls.TextBox
    Protected WithEvents ddlIDSSort As System.Web.UI.WebControls.DropDownList
    Protected WithEvents ddlOrderGoods As System.Web.UI.WebControls.DropDownList
    Protected WithEvents ddlFOBOrHD As System.Web.UI.WebControls.DropDownList
    Protected WithEvents ddlTerritory As System.Web.UI.WebControls.DropDownList
    Protected WithEvents ibtnExportPDF As System.Web.UI.WebControls.ImageButton
    Protected WithEvents ibtnGO As System.Web.UI.WebControls.ImageButton
    Protected WithEvents lnkViewShoppingCart As System.Web.UI.WebControls.LinkButton
    Protected WithEvents lnkNotUseSignedInAccount As System.Web.UI.WebControls.LinkButton

    Protected WithEvents lnkFrontPage As System.Web.UI.WebControls.LinkButton
    Protected WithEvents lblTitle As System.Web.UI.WebControls.Label
    Protected WithEvents lblEmailLoggedIn As System.Web.UI.WebControls.Label
    Protected WithEvents lblEmail As System.Web.UI.WebControls.Label
    Protected WithEvents loggedInSection As System.Web.UI.HtmlControls.HtmlGenericControl
    Protected WithEvents ddlCountry As System.Web.UI.WebControls.DropDownList

    'NOTE: The following placeholder declaration is required by the Web Form Designer.
    'Do not delete or move it.
    Private designerPlaceholderDeclaration As System.Object

    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        'CODEGEN: This method call is required by the Web Form Designer
        'Do not modify it using the code editor.
        InitializeComponent()
    End Sub

#End Region

    Public Event OKClick(ByVal conPointID As Int32, ByVal IDSSort As Int32, ByVal quantity As Int32, ByVal discount As Decimal, ByVal showFOB As Boolean, ByVal ownerId As Int32, ByVal territoryId As Int32, ByVal countryId As Int32)
    Public Event ExportPDFClick()
    Public Event ViewShoppingCartClick()

    Private Sub LoadTerritoryByCountry()
        If (ddlCountry.SelectedIndex >= 0) Then
            Try
                ddlTerritory.DataSource = TerritoryService.GetTerritoriesForIDSByCountry(Convert.ToInt32(ddlCountry.SelectedValue))
                ddlTerritory.DataTextField = TerritoryColumns.Description.ToString()
                ddlTerritory.DataValueField = TerritoryColumns.TerritoryID.ToString()
                ddlTerritory.DataBind()
            Catch ex As Exception
            End Try
        End If
    End Sub

    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not IsPostBack Then
            If RequestContext.CurrentUser.USER_TYPE = UserType.Customer Then
                Me.txtDiscount.Visible = False
            Else
                Me.txtDiscount.Visible = True
                txtDiscount.Text = Request("discount")
            End If

            Me.chkShowFOB.Visible = True
            chkShowFOB.Checked = Convert.ToBoolean(Convert.ToInt32(Request("showfob")))

            Dim cpc As ConPointCollection = ConPointService.GetConPointsListForIDS()

            Me.ddlConPoint.DataSource = cpc
            Me.ddlConPoint.DataTextField = ConPointColumns.Description.ToString()
            Me.ddlConPoint.DataValueField = ConPointColumns.ConPointID.ToString()
            Me.ddlConPoint.DataBind()

            Me.ddlIDSSort.DataSource = IDSSortService.GetIDSSortsOnIDS()
            Me.ddlIDSSort.DataTextField = IDSSortColumns.Name.ToString()
            Me.ddlIDSSort.DataValueField = IDSSortColumns.IDSSortID.ToString()
            Me.ddlIDSSort.DataBind()

            Me.ddlIDSSort.Items.Insert(0, New ListItem("[All]", "-1"))

            ddlOrderGoods.Visible = False
            'ddlOrderGoods.DataSource = OfficeService.GetOffices(RequestContext.CurrentUser.US_ID_PK)
            'ddlOrderGoods.DataTextField = OfficeColumns.OfficeName.ToString()
            'ddlOrderGoods.DataValueField = OfficeColumns.OfficeID.ToString()
            'ddlOrderGoods.DataBind()

            'ddlOrderGoods.Items.Insert(0, New ListItem("[No Order Goods]", "-1"))

            'If (RequestContext.CurrentUser.USER_TYPE <> UserType.Customer _
            '    AndAlso RequestContext.CurrentUser.USER_TYPE <> UserType.Sales) Then
            '    ddlOrderGoods.Items.Insert(0, New ListItem("[ALL Owner]", "-2"))
            'End If

            'Try
            '    ddlOrderGoods.SelectedIndex = ddlOrderGoods.Items.IndexOf(ddlOrderGoods.Items.FindByValue(RequestContext.OwnerID.ToString()))
            'Catch ex As Exception
            'End Try

            ddlCountry.DataSource = CountryService.GetCountriesForIDS()
            ddlCountry.DataTextField = CountryColumns.CountryName.ToString()
            ddlCountry.DataValueField = CountryColumns.CountryID.ToString()
            ddlCountry.DataBind()

            If (RequestContext.CountryID > -1) Then
                ddlCountry.SelectedIndex = ddlCountry.Items.IndexOf(ddlCountry.Items.FindByValue(RequestContext.CountryID.ToString()))
            End If

            LoadTerritoryByCountry()

            If (RequestContext.TerritoryID > -1) Then
                Try
                    ddlTerritory.SelectedIndex = ddlTerritory.Items.IndexOf(ddlTerritory.Items.FindByValue(RequestContext.TerritoryID.ToString()))
                Catch ex As Exception
                End Try

                ddlFOBOrHD.SelectedIndex = 1
            Else
                ddlFOBOrHD.SelectedIndex = 0
            End If

            Dim cpHTML As String = ""
            Dim loadingPortHTML As String = ""
            Dim i As Integer
            For i = 0 To cpc.Count - 1
                cpHTML += String.Format("cpData[{0}] = ""{1}"";{2}", i, Server.HtmlEncode(cpc(i).ContainerLoading), Environment.NewLine)
                loadingPortHTML += String.Format("cpLoadingPortData[{0}] = ""{1}"";{2}", i, Server.HtmlEncode(cpc(i).LoadingPort), Environment.NewLine)
            Next

            ltrJS.Text = "<script>var cpData = new Array(); var cpLoadingPortData = new Array();"
            ltrJS.Text += cpHTML
            ltrJS.Text += loadingPortHTML
            ltrJS.Text += "</script>"

            Try
                ddlConPoint.SelectedIndex = ddlConPoint.Items.IndexOf(ddlConPoint.Items.FindByValue(RequestContext.ConPointID.ToString()))
            Catch ex As Exception
            End Try


            Dim boType As Int32 = -1
            If Not Request.QueryString("type") Is Nothing Then
                boType = RequestContext.BOType
            End If

            Dim target As Int32 = -1

            txtQty.Text = RequestContext.Quantity.ToString()
            Try
                ddlIDSSort.SelectedIndex = ddlIDSSort.Items.IndexOf(ddlIDSSort.Items.FindByValue(Request.QueryString("sort")))
            Catch ex As Exception

            End Try
        End If
        HandleFrontPageClick()
        'Shoping user sign in
        If Not (Request.Item("__EVENTTARGET") Is Nothing) AndAlso Request.Item("__EVENTTARGET").ToString = "showShoppingCartScreen" Then
            'TODO: no need to use it
            'GetShoppingListFromDB(ShoppingConext.ShopingUserId)
            lnkViewShoppingCart_Click(lnkViewShoppingCart, Nothing)
        End If

        ShowAccount()
    End Sub

    Private Sub ShowAccount()
        loggedInSection.Visible = (ShoppingConext.ShopingUserId > 0)
        If (ShoppingConext.ShopingUserId > 0) Then
            lblEmail.Text = ShoppingConext.ShopingUserEmail
        End If
    End Sub

    Private Sub GetShoppingListFromDB(ByVal shopingUserId As Integer)
        If (shopingUserId > 0) Then
            Dim oCollection As New Collection
            If (Not Session(Constant.SS_SHOPPING_LIST) Is Nothing) Then
                oCollection = DirectCast(Session(Constant.SS_SHOPPING_LIST), Collection)
            End If

            Dim shoppingOrderCol As ShoppingOrderCollection = ShoppingListService.GetShoppingOrderByShoppingUserId(shopingUserId)
            If (ShoppingConext.ShopingSelectedConsolidation > 0) Then
                Dim shoppingOrderItem As New ShoppingOrder
                Dim bExisted As Boolean = False
                Dim conPointIDList As New ListItemCollection

                If (Not shoppingOrderCol Is Nothing AndAlso shoppingOrderCol.Count > 0) Then
                    For Each item As ShoppingOrder In shoppingOrderCol
                        If (ShoppingConext.ShopingSelectedConsolidation = item.ConPointID) Then
                            shoppingOrderItem = item
                            bExisted = True
                        End If
                        If (Not conPointIDList.FindByValue(item.ConPointID.ToString()) Is Nothing) Then
                            conPointIDList.Add(item.ConPointID.ToString())
                        End If
                    Next
                End If
                If (bExisted) Then 'Load a existing saved list & current selection if have
                    If (Not shoppingOrderItem Is Nothing) Then
                        Session("txtQty20Cont") = shoppingOrderItem.Qty20
                        Session("txtQty40Cont") = shoppingOrderItem.Qty40
                        Session("txtQty40HiCube") = shoppingOrderItem.Qty40HC

                        Session("txtOrderNo") = shoppingOrderItem.OrderNo
                        Session("txtHalfPallet") = shoppingOrderItem.HalfPalletSpaces
                        Session("txtExistingOrderVolume") = shoppingOrderItem.FilledVolume

                        Session("rdPartOrder") = shoppingOrderItem.OrderType

                        Session("ddlCountry") = shoppingOrderItem.DestinationCountryId
                    End If
                    Dim shoppingItemsList As ShoppingListCollection = ShoppingListService.GetShoppingListByShoppingUserIdAndConPoint(shopingUserId, ShoppingConext.ShopingSelectedConsolidation)
                    Dim previousShoppingList As New Collection
                    If (Not shoppingItemsList Is Nothing AndAlso shoppingItemsList.Count > 0) Then
                        Dim item As New shoppingItem
                        For Each shoppingItem As ShoppingList In shoppingItemsList
                            item = New shoppingItem
                            With item
                                .ItemNo = shoppingItem.IDSSort
                                .ProductCode = shoppingItem.ProductCode
                                .Description = shoppingItem.Description
                                .Quantity = shoppingItem.Qty
                                .UnitDesc = shoppingItem.UnitSetting
                                Try
                                    .UnitSettingID = shoppingItem.UnitSettingID
                                Catch ex As Exception
                                End Try

                                .UnitPrice = shoppingItem.UnitPrice
                                .Total = shoppingItem.TotalPrice
                                .UnitWeight = Convert.ToDecimal(shoppingItem.UnitWeight)
                                .Priority = shoppingItem.PriorityIndex
                                .BulkOrderId = shoppingItem.BulkOrderId
                                .TerritoryID = shoppingItem.TerritoryID
                                .MinQtyVolume = Convert.ToDecimal(shoppingItem.MinQtyVolume)
                                .CountryId = shoppingOrderItem.ConPointID
                            End With
                            previousShoppingList.Add(item)
                        Next
                        If (Not oCollection Is Nothing AndAlso oCollection.Count > 0) Then
                            For i As Integer = 1 To oCollection.Count
                                previousShoppingList.Add(DirectCast(oCollection(i), shoppingItem))
                            Next
                        End If
                        Session(Constant.SS_SHOPPING_LIST) = previousShoppingList
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub btnExportPDF_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub ibtnGO_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ibtnGO.Click
        Dim discount As Decimal = 0
        Dim chkFOB As Boolean = False
        chkFOB = chkShowFOB.Checked

        If RequestContext.CurrentUser.USER_TYPE <> UserType.Customer _
            Or RequestContext.CurrentUser.IS_ADMIN = True Then
            Try
                discount = Decimal.Parse(txtDiscount.Text)
            Catch ex As Exception
            End Try
        End If

        Dim idsSort As Integer = -1 ' [All]
        Try
            idsSort = Convert.ToInt32(ddlIDSSort.SelectedItem.Value)
        Catch ex As Exception

        End Try

        Dim qty As Integer = 0
        Try
            qty = Convert.ToInt32(txtQty.Text)
        Catch ex As Exception
        End Try

        Dim territoryId As Integer = -1
        Dim countryId As Integer = -1
        If (ddlFOBOrHD.SelectedIndex > 0 AndAlso ddlCountry.SelectedIndex >= 0 AndAlso ddlTerritory.SelectedIndex >= 0) Then  ' not use FOB
            territoryId = Convert.ToInt32(ddlTerritory.SelectedItem.Value)
            countryId = Convert.ToInt32(ddlCountry.SelectedItem.Value)
        End If

        'RaiseEvent OKClick(Int32.Parse(ddlConPoint.SelectedItem.Value), _
        '            idsSort, qty, discount, chkFOB, Convert.ToInt32(ddlOrderGoods.SelectedItem.Value), Convert.ToInt32(ddlFOBOrHD.SelectedItem.Value))
        RaiseEvent OKClick(Int32.Parse(ddlConPoint.SelectedItem.Value), _
                    idsSort, qty, discount, chkFOB, -2, territoryId, countryId)  ' -2 ~ [ALL]
    End Sub

    Private Sub ibtnExportPDF_Click(ByVal sender As System.Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles ibtnExportPDF.Click
        RaiseEvent ExportPDFClick()
    End Sub

    Private Sub lnkViewShoppingCart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkViewShoppingCart.Click
        Dim idsStockParams As New Common.IMStockReportParams
        With idsStockParams
            .FOBOrHD = Convert.ToInt16(ddlFOBOrHD.SelectedValue)
            Try
                .IDSSort = Convert.ToInt32(ddlIDSSort.SelectedItem.Value)
            Catch ex As Exception
            End Try
            Try
                .Quantity = Convert.ToInt32(txtQty.Text)
            Catch ex As Exception
            End Try
            Try
                .Discount = Convert.ToInt32(txtDiscount.Text)
            Catch ex As Exception
            End Try
            .Showfob = chkShowFOB.Checked
            If (ddlFOBOrHD.SelectedIndex > 0 AndAlso ddlCountry.SelectedIndex >= 0 AndAlso ddlTerritory.SelectedIndex >= 0) Then ' not use FOB
                .TerritoryId = Convert.ToInt32(ddlTerritory.SelectedItem.Value)
                .CountryId = Convert.ToInt32(ddlCountry.SelectedItem.Value)
            End If
            .ConPointID = RequestContext.ConPointID
            .DoReport = RequestContext.DoReport
        End With
        Session("IMStockReportParams") = idsStockParams

        RaiseEvent ViewShoppingCartClick()
    End Sub

    Private Sub lnkNotUseSignedInAccount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkNotUseSignedInAccount.Click
        ShoppingConext.ShopingUserId = 0
        ShoppingConext.ShopingUserEmail = ""
        ShoppingConext.ShopingSelectedConsolidation = Nothing
        ShowAccount()
    End Sub

    Private Sub HandleFrontPageClick()
        'Shopping List
        Dim oCollection As New Collection
        If (Not System.Web.HttpContext.Current.Session(Constant.SS_SHOPPING_LIST) Is Nothing) Then
            oCollection = DirectCast(System.Web.HttpContext.Current.Session(Constant.SS_SHOPPING_LIST), Collection)
        End If
        Dim confirm As String = ""
        If (oCollection.Count <> 0) Then
            confirm = "1"
        End If
        lnkFrontPage.Attributes.Add("onclick", String.Format("javascript:return ShowConfirm('{0}');", confirm))
    End Sub

    Private Sub lnkFrontPage_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lnkFrontPage.Click
        Session(Constant.SS_SHOPPING_LIST) = Nothing 'Shopping List
        Session(Constant.SS_SHOPPING_USER) = Nothing 'Shopping User
        Session(Constant.txtExistingOrderVolume) = Nothing ' clear shopping list
        Session(Constant.txtHalfPallet) = Nothing ' clear shopping list
        Session(Constant.txtOrderNo) = Nothing ' clear shopping list
        Session(Constant.txtQty20Cont) = Nothing ' clear shopping list
        Session(Constant.txtQty40Cont) = Nothing ' clear shopping list
        Session(Constant.txtQty40HiCube) = Nothing ' clear shopping list
        Session(Constant.rdPartOrder) = Nothing ' clear shopping list
        Session(Constant.ddlCountry) = Nothing ' clear shopping list
        RequestContext.CurrentDestinationCountry = Nothing
        Session(Constant.SS_CONPOINT_ID) = Nothing
        Session(ShoppingConext.ShopingSelectedConsolidation.ToString()) = Nothing
        Session(Constant.SS_SELECTED_CONPOINT_ID) = Nothing
        Me.Page.Response.Redirect("Start.aspx")
    End Sub

    Public Function GetSelectedPriceType() As String
        Return ddlFOBOrHD.SelectedItem.Text
    End Function

    Public Function DeliveryAndPricingID() As String
        Return ddlFOBOrHD.SelectedItem.Value
    End Function
    Public Function GetSelectedTeritory() As String
        Try
            Return ddlTerritory.SelectedItem.Text
        Catch ex As Exception
        End Try
        Return ""
    End Function

    Public Function TeritoryID() As String
        Try
            Return ddlTerritory.SelectedItem.Value
        Catch ex As Exception
        End Try
        Return ""
    End Function

    Public Function GetSelectedCountry() As String
        Try
            Return ddlCountry.SelectedItem.Text
        Catch ex As Exception
        End Try
        Return ""
    End Function

    Private Sub ddlCountry_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ddlCountry.SelectedIndexChanged
        LoadTerritoryByCountry()
    End Sub
End Class
